﻿using Mozhi.Abp.Domain.BasicData.Repositories;
using Mozhi.Abp.Domain.BasicData;
using mozhi.smarterp.Business.Products.Repositories;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.Business.Products.Services
{
    public class ProductSaleSettingManager : DomainService
    {
        private IProductRepository _productRepository;
        private IUnitRepository _unitRepository;
        private IGuidGenerator _guidGenerator;
        private IProductAuxiliaryUnitRepository _auxiliaryUnitRepository;
        private IProductSaleSettingRepository _repository;

        public ProductSaleSettingManager(IProductRepository productRepository, IUnitRepository unitRepository, IGuidGenerator guidGenerator,
            IProductAuxiliaryUnitRepository auxiliaryUnitRepository, IProductSaleSettingRepository repository)
        {
            _productRepository = productRepository;
            _unitRepository = unitRepository;
            _guidGenerator = guidGenerator;
            _auxiliaryUnitRepository = auxiliaryUnitRepository;
            _repository = repository;
        }

        public async Task<ProductSaleSetting> GetAsync(Guid? id, Guid? productId, Guid saleUnitId)
        {
            var matchCount = await _repository.GetCountAsync(productId, id);

            if (matchCount > 0)
                throw new UserFriendlyException($"产品：{productId}销售信息已存在", "100000");



            ProductSaleSetting saleSetting;

            if (id.HasValue)
            {
                saleSetting = await _repository.GetAsync(id.Value);

                if (saleSetting == null)
                    throw new UserFriendlyException($"产品销售设置：{id.Value}不存在");

                var product = await _productRepository.GetAsync(saleSetting.ProductId);

                var saleUnit = await _unitRepository.GetAsync(saleUnitId);

                var auxiliaryUnit = product.BasicUnitId != saleUnitId ? await _auxiliaryUnitRepository.GetAsync(saleSetting.ProductId, saleUnitId) : null;

                saleSetting.Change(product, saleUnit, auxiliaryUnit);
            }
            else
            {
                var product = await _productRepository.GetAsync(productId.Value);

                var saleUnit = await _unitRepository.GetAsync(saleUnitId);

                var auxiliaryUnit = product.BasicUnitId != saleUnitId ? await _auxiliaryUnitRepository.GetAsync(productId.Value, saleUnitId) : null;

                saleSetting = new ProductSaleSetting(_guidGenerator.Create(), product, saleUnit, auxiliaryUnit);
            }
            return saleSetting;
        }
    }
}
